package org.ccay.ws;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;

import org.ccay.enumerable.EnumItem;
import org.ccay.enumerable.wsrs.EnumerableConverter;

@Provider
@SuppressWarnings("unchecked")
public class CustomParamConverterProvider implements ParamConverterProvider {
	@Override
	public <T> ParamConverter<T> getConverter(Class<T> rawType,
			Type genericType, Annotation[] annotations) {
		if(rawType == Boolean.class ){
			return (ParamConverter<T>) new BooleanConverter();
		}
		if(EnumItem.class.isAssignableFrom((Class<?>) rawType)){
			if(rawType.isEnum()){
				return (ParamConverter<T>) new EnumerableConverter(rawType);
			}
			if(genericType instanceof ParameterizedType){
				Class<?> type = (Class<?>)((ParameterizedType)genericType).getActualTypeArguments()[0];
				return (ParamConverter<T>) new EnumerableConverter(type);
			}
		}
		
		return null;
	}
	
	/**
	 * 布尔值类型转换
	 * @author chaowangbang
	 *
	 */
	class BooleanConverter implements ParamConverter<Boolean>{
		@Override
		public Boolean fromString(String value) {
			if(value == null){
				return false;
			}
			String val = value.trim();
			if(val.matches("^\\d+$")){
				return Integer.parseInt(val) != 0;
			}else if(!val.equalsIgnoreCase("true")){
				return false;
			}
			return true;
		}

		@Override
		public String toString(Boolean value) {
			return Boolean.toString(value);
		}
	}

}
